const fs = require('fs');
const https = require('https');
const express = require('express');
const serveStatic = require('serve-static');

const { listen, key, cert, static: staticConfig } = require('./config');

// express app
const app = express();
staticConfig.forEach(({ url, path, options }) => {
	app.use(url, serveStatic(path, options));
});

// http server
const server = https.createServer({
	key: fs.readFileSync(key),
	cert: fs.readFileSync(cert)
});
server.on('request', app);

// socket io
const socketio = require('socket.io');
let io = socketio(server);
io.on('connection', socket => {
	socket.emit('id', socket.id);

	socket.on('join', room => {
		socket.join(room);
		socket.to(room).emit('data', {
			room,
			type: 'join'
		});
	});

	socket.on('send', data => {
		socket.to(data.room).emit('data', data);
	});

	socket.on('disconnect', () => {
		io.emit('leave', {
			type: 'leave'
		});
	});
});


server.listen(listen);
